<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MicrosoftDateFormatter
 *
 * @author JeyDotC
 */
class MicrosoftDateFormatter {

    public static function toJSON($date, $format = "d/m/Y") {
        $timestamp = DateTime::createFromFormat($format, $date)->getTimestamp();
        $result = "/Date(" . $timestamp * 1000 . ")/";

        return $result;
    }

    public static function fromJSON($jsonDate, $format = "M d Y") {
        $timeSring = str_replace(array("Date", "/", "\\", "(", ")"), "", $jsonDate);
        $timeStamp = 0;
        $timeDifferece = 0;
        $tDir = 1;

        if (strpos($timeSring, "+") !== false) {
            $parts = explode("+", $timeSring);
            $timeStamp = (int) $parts[0];
            $timeDifferece = $parts[1];
        } else if (strpos($timeSring, "-") !== false) {
            $parts = explode("-", $timeSring);
            $timeStamp = $parts[0];
            $timeDifferece = $parts[1];
            $tDir = -1;
        }

        $dif = 0;
        $dif = $tDir * self::calculateTimeDifference($timeDifferece);
        $milis = $timeStamp + $dif;

        return date($format, ($timeStamp/1000));
    }

    private static function calculateTimeDifference($timeString) {
        $hours = (int) substr($timeString, 0, 2);
        $minutes = (int) substr($timeString, -2);

        return $hours * 3600000 + $minutes * 600000;
    }

}

?>
